package com.bandaotixi.cashier.api.core.mybatis;

import cn.hutool.extra.spring.SpringUtil;
import com.bandaotixi.cashier.api.common.model.KeyValue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SqlUtil {
    public static List<KeyValue<Long, Long>> relational(String table, String keyColumn, String valueColumn) {
        return relational(table, keyColumn, valueColumn, null);
    }

    /**
     * 查询关系表数据
     */
    public static List<KeyValue<Long, Long>> relational(String table, String keyColumn, String valueColumn, Map<String,Object> where) {
        CommonQueryMapper mapper = SpringUtil.getBean(CommonQueryMapper.class);
        return mapper.relational(table, keyColumn, valueColumn, where);
    }

    /**
     * 新增或修改
     */
    public static int upsert(String table, Map<String, Object> data) {
        CommonQueryMapper mapper = SpringUtil.getBean(CommonQueryMapper.class);
        return mapper.upsert(table, data);
    }

    public static int batchUpsert(String table, List<Map<String, Object>> dataList) {
        CommonQueryMapper mapper = SpringUtil.getBean(CommonQueryMapper.class);
        return mapper.batchUpsert(table, dataList);
    }

    public static int relationalBatchUpsert(String table, String keyColumn, String valueColumn, List<KeyValue<Long, Long>> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return 0;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (KeyValue<Long, Long> item : dataList) {
            Map<String, Object> map = Map.of(keyColumn, item.getKey(), valueColumn, item.getValue());
            list.add(map);
        }
        return batchUpsert(table, list);
    }

    public static int delete(String table, Map<String,Object> where) {
        CommonQueryMapper mapper = SpringUtil.getBean(CommonQueryMapper.class);
        return mapper.delete(table, where);
    }
}
